<?php

namespace backend\controllers;

use backend\models\PackageEaseTransfer;
use PHPUnit\Framework\Exception;
use Yii;
use backend\models\PackageEase;
use backend\models\PackageEaseSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use backend\models\Country;
use yii\helpers\Json;

/**
 * PackageEaseController implements the CRUD actions for PackageEase model.
 */
class PackageEaseController extends Controller
{
    public $layout = 'yue-juan';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all PackageEase models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->request->post('hasEditable')) {
            $model = $this->findModel(Yii::$app->request->post('editableKey'));
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $posted = current($_POST['PackageEase']);
            $post = ['PackageEase' => $posted];
            if ($model->load($post)) {
                $editableAttribute = Yii::$app->request->post('editableAttribute');
                if ($model->save()) {
//                    $out = ['output' => $model->$editableAttribute, 'message' => ''];
                    if ($editableAttribute == 'type') {
                        $output = Yii::$app->params['package_ease_type'][$model->type];
                    } elseif ($editableAttribute == 'level') {
                        $output = Yii::$app->params['package_ease_level'][$model->level];
                    } elseif ($editableAttribute == 'province') {
                        $arr_province = Country::localCity('`pid`=0 AND `order`>0');
                        $output = $arr_province[$model->$editableAttribute];
                    } elseif ($editableAttribute == 'creditor') {
                        $output = preg_replace('/中国|资产管理股份有限公司/', '', $model->creditor);
                    } else {
                        $output = $model->$editableAttribute;
                    }
                    $out = ['output' => $output, 'message' => ''];
                } else {
                    $out = ['output' => '', 'message' => serialize($model->getFirstErrors())];
                }
            } else {
                $out = ['output' => '', 'message' => 'not loaded'];
            }
            return $out;
        }


        $searchModel = new PackageEaseSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PackageEase model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new PackageEase model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PackageEase();
        $transferModel = new PackageEaseTransfer();
        $post = Yii::$app->request->post();

        if (Yii::$app->request->isAjax && $model->load($post)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load($post)) {

            $model->principal_interest = (float)$model->principal + (float)$model->interest;
            $model->owner = Yii::$app->user->id;
            $transferModel->load($post);

            $valid = $model->validate() && $transferModel->validate();

            if ($valid) {
                $transaction = Yii::$app->db->beginTransaction();
                try {
                    $model->created_at = date('Y-m-d H:i:s');
                    $model->city = $model->city ? implode(',', $model->city) : '';
                    if ($flag = $model->save(false)) {
                        $transferModel->package_id = $model->id;
                        $transferModel->created_at = date('Y-m-d H:i:s');
                        $flag = $transferModel->save(false);
                    }
                    if ($flag) {
                        $transaction->commit();
                        Yii::$app->session->addFlash('success', '创建成功');
                        return $this->redirect(['index']);
//                        return $this->redirect(['update', 'id' => $model->id]);
                    } else {
                        $transaction->rollBack();
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            } else {
                Yii::$app->session->addFlash('danger', serialize($model->getFirstErrors()) . serialize($transferModel->getFirstErrors()));
                return $this->redirect(Yii::$app->request->referrer);
            }
        } else {
            $transferModel->transfer = 2;
            return $this->render('create', [
                'model' => $model,
                'transferModel' => $transferModel,
            ]);
        }
    }

    /**
     * Updates an existing PackageEase model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $post = Yii::$app->request->post();
        if ($transferModel = PackageEaseTransfer::findOne(['package_id' => $id])) {

        } else {
            $transferModel = new PackageEaseTransfer();
        }

        $count_transfer = PackageEaseTransfer::find()->where(['package_id' => $id])->count();
        if ($count_transfer == 0) {
            $transferModel = new PackageEaseTransfer();
        } elseif ($count_transfer == 2) {
            $transferModels = PackageEaseTransfer::findAll(['package_id' => $id]);
            $transferModel = $transferModels[0];
            $transferModel2 = $transferModels[1];
        } elseif ($count_transfer == 1) {
            $transferModel = PackageEaseTransfer::findOne(['package_id' => $id]);
            if ($transferModel->transfer == '2') {//居间人，需要再填写持有人信息
                $transferModel2 = new PackageEaseTransfer();
//                $transferModel2->transfer = 1;
//                $transferModel2->wish = $transferModel->wish;
//                $transferModel2->detail = $transferModel->detail;
            }
        }


        if (Yii::$app->request->isPost) {

            if ($post['PackageEaseTransfer']) {
                $transferModel->load($post);
                $transferModel->package_id = $id;
                if ($transferModel->save()) {
                    Yii::$app->session->setFlash('kv-detail-success', '保存成功');
                } else {
                    Yii::$app->session->setFlash('kv-detail-warning', serialize($transferModel->getFirstErrors()));
                }
            } else {
                $model->load($post);
                $model->city = $model->city ? implode(',', $model->city) : '';
                if ($model->save()) {
                    Yii::$app->session->setFlash('kv-detail-success', '保存成功');
                } else {
                    Yii::$app->session->setFlash('kv-detail-warning', serialize($model->getFirstErrors()));
                }
            }
//            return $this->redirect('index');
            return $this->render('update', [
                'model' => $model,
                'transferModel' => $transferModel,
            ]);
        } else {
//            $model->city = explode(',', $model->city);
            return $this->render('update', [
                'model' => $model,
                'transferModel' => $transferModel,
                'transferModel2' => $transferModel2 ? $transferModel2 : '',
            ]);
        }
    }

    /**
     * Deletes an existing PackageEase model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if ($model->owner == Yii::$app->user->id) {
            $model->delete();
            Yii::$app->session->setFlash('success', '删除成功');
        } else {
            Yii::$app->session->setFlash('warning', '只能删除自己创建的资产包');
        }

        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionEditableTransfer()
    {
        if (Yii::$app->request->post('hasEditable')) {
            $model = $this->findModel(Yii::$app->request->post('editableKey'));
            \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $posted = current($_POST['PackageEase']);
            $transferModel = PackageEaseTransfer::findOne(['package_id' => $model->id]);
            $transferModel->remark = $posted['packageEaseTransfer.remark'];
//            $editableAttribute = Yii::$app->request->post('editableAttribute');
            if ($transferModel->save()) {
                $out = ['output' => mb_strcut($transferModel->remark, 0, 30), 'message' => ''];
            } else {
                $out = ['output' => '', 'message' => serialize($transferModel->getFirstErrors())];
            }
            return $out;
        }
    }

    /**
     * Finds the PackageEase model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return PackageEase the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PackageEase::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionImport()
    {
        if (empty($_FILES['package_file'])) {
            Yii::$app->session->setFlash('danger', '请先选择要上传的文件');
            return $this->redirect(Yii::$app->request->referrer); // terminate
        }
        $package_file = $_FILES['package_file'];
        $success = null;
        $filename = $package_file['name'];
        $ext = explode('.', basename($filename));
        $path = "uploads" . DIRECTORY_SEPARATOR . date('Ymd');
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $extension = array_pop($ext);
        if (!in_array($extension, ['xlsx', 'xls'])) {
            Yii::$app->session->setFlash('danger', '请上传excel格式的文件');
            return $this->redirect(Yii::$app->request->referrer); // terminate
        }
        $target = $path . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . $extension;
        if (move_uploaded_file($package_file['tmp_name'], $target)) {
            $success = true;
//            Yii::$app->session->setFlash('success', '上传成功');
            $this->processData($target);
        } else {
            Yii::$app->session->setFlash('danger', '上传失败');
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

    public function actionDownloadTemplate()
    {
        return Yii::$app->response->sendFile('package_import_template.xlsx');
    }

    public function processData($filename)
    {
        $packageEaseModel = new PackageEase();
        $transferModel = new PackageEaseTransfer();
        $imported_data = \moonland\phpexcel\Excel::import(
            $filename,
            [
                'setFirstRecordAsKeys' => true, // if you want to set the keys of record column with first record, if it not set, the header with use the alphabet column on excel.
                'setIndexSheetByName' => true, // set this if your excel data with multiple worksheet, the index of array will be set with the sheet name. If this not set, the index will use numeric.
                'getOnlySheet' => 'Sheet1', // you can set this property if you want to get the specified sheet from the excel data with multiple worksheet.
            ]);
        if (is_array($imported_data) && count($imported_data) > 0) {

            $package_labels = $packageEaseModel->attributeLabels();
            $transfer_labels = $transferModel->attributeLabels();

            $success_count = 0;
            $failed_count = 0;
            foreach ($imported_data as $key => $item) {

                //名称为空则执行下一个循环
                if (empty($item[$packageEaseModel->getAttributeLabel('title')])) {
                    continue;
                }

                $packageEaseCloneModel = clone $packageEaseModel;
                foreach ($package_labels as $field => $label) {
                    switch ($field) {
                        case 'type':
                            $package_ease_type = array_flip(Yii::$app->params['package_ease_type']);
                            $type = $package_ease_type[$item[$label]];
                            $packageEaseCloneModel->type = $type ? $type : 0;
                            break;
                        case 'province':
                            $province = Country::findOne(['title' => $item[$label]])->id;
                            $packageEaseCloneModel->province = $province ? $province : 0;
                            break;
                        case 'city':
                            $city = Country::find()->where("`title` = '" . $item[$label] . "' AND `pid` > 0")->one()->id;
                            $packageEaseCloneModel->city = $city ? $city : 0;
                            break;
                        default:
                            $packageEaseCloneModel->$field = $item[$label];
                    }
                }
                $packageEaseCloneModel->owner = Yii::$app->user->id;
                $packageEaseCloneModel->created_at = date('Y-m-d H:i:s');
                if ($packageEaseCloneModel->save()) {
                    $package_id = $packageEaseCloneModel->id;
                    //居间人
                    $transferCloneModel = clone $transferModel;
                    foreach ($transfer_labels as $field => $label) {
                        switch ($field) {
                            case 'package_id':
                                $transferCloneModel->package_id = $package_id;
                                break;
                            case 'method':
                                $transfer_method = array_flip(Yii::$app->params['transfer_method']);
                                $method = $transfer_method[$item[$label]];
                                $transferCloneModel->method = $method ? $method : 0;
                                break;
                            case 'transfer':
                                $transferCloneModel->transfer = 2;
                                break;
                            case 'contact':
                                $transferCloneModel->contact = $item['居间人'];
                                break;
                            default:
                                $transferCloneModel->$field = $item[$label];
                        }
                    }
                    $transferCloneModel->created_at = date('Y-m-d H:i:s');
                    if ($transferCloneModel->save() == false) {
                        Yii::$app->session->addFlash('danger', $item['名称'] . '居间人信息未导入' . serialize($transferCloneModel->getFirstErrors()));
                    }
                    //持包人
                    $transferCloneSecModel = clone $transferModel;
                    $transferCloneSecModel->package_id = $package_id;
                    $transferCloneSecModel->transfer = 1;
                    $transferCloneSecModel->contact = $item['持包人'];
                    $transferCloneSecModel->phone = $item['持包人电话'];
                    $transferCloneSecModel->address = $item['持包人地址'];
                    $transferCloneSecModel->email = $item['持包人邮箱'];
                    $transferCloneSecModel->position = $item['持包人职位'];
                    $transferCloneSecModel->remark = $item['持包人备注'];
                    $transferCloneSecModel->created_at = date('Y-m-d H:i:s');
                    if ($transferCloneSecModel->save() == false) {
                        Yii::$app->session->addFlash('danger', $item['名称'] . '持包人信息未导入 ' . serialize($transferCloneSecModel->getFirstErrors()));
                    }

                    $success_count++;
                } else {
                    $failed_count++;
                    Yii::$app->session->addFlash('danger', $item['名称'] . '未导入' . serialize($packageEaseCloneModel->getFirstErrors()));
                }

            }
            Yii::$app->session->addFlash('success', '成功导入' . $success_count . '条。失败' . $failed_count . '条。');

        } else {
            //表中无数据
            Yii::$app->session->setFlash('danger', '表中无数据');
        }
    }
}
